<?php
/*
This sends a little bit of JSON to say if the user is logged in. 
*/

require_once( 'core.php' );
require_once( 'current_user_api.php' );

auth_ensure_user_authenticated( );
//helper_begin_long_process( );

$t_plugin_path = config_get( 'plugin_path' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'TableMetadata.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'JSONstore.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'MetadataStandards.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'ProjectsMetadata.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'TableOutputs.php' );

/*
 Turn this on to update the metadata standards
 
$MetadataStandards = new MetadataStandards;
$MetadataStandards->saveMetadata();
*/


$authHashPrefix = plugin_config_get( 'authHashPrefix' );
$refineHumanURI = plugin_config_get( 'refineBaseURI' ); //for human linking
$refineURI = plugin_config_get( 'refineLocalURI' );
if(!$refineURI){
	$refineURI = plugin_config_get( 'refineBaseURI' );
}

# extracts the user information for the currently logged in user
# and prefixes it with u_
$f_user_id = gpc_get_int( 'id', auth_get_current_user_id() );
$row = user_get_row( $f_user_id );

extract( $row, EXTR_PREFIX_ALL, 'u' );
$u_email = user_get_email( $u_id );
$u_realname = user_get_realname( $u_id );


if(!isset($_GET["grProject"])){
	$GRprojectID =  false;
}
else{
	$GRprojectID = $_GET["grProject"]; 
}



$tableMetaObj = new TableMetadata;
$tableMetaObj->refineURI = $refineURI;
$tableMetaObj->currentUserID = $f_user_id;
$tableMetaObj->currentUserName = $u_username;
$tableMetaObj->currentUserRole = "field documentation";
$tableMetaObj->GRprojectID = $GRprojectID;
$tableMetaObj->get_metadata();
$tableMetaObj = check_edit_resolution($tableMetaObj); //now check on the status of the edit issue
$tableMetaObj = check_metadata_fieldDes_resolution($tableMetaObj); //now check on status of the metadata desription and field documentation issues
$tableMetadata = $tableMetaObj->currentMetadata;

if(!isset($tableMetadata["columns"]) || !$tableMetadata["issueIDs"]["editResolved"]){
	$tableMetadata["columns"] = array();
	$totalCols = "[None Ready for Documentation]";
	$remainingCols = "[Not yet determined]";
}
else{
	$tableMetaObj->count_column_documentation();
	$tableMetadata = $tableMetaObj->currentMetadata;
	$totalCols = $tableMetaObj->numberColumns;
	$remainingCols = $totalCols - ($tableMetaObj->columnsDocumented);
}



if(!check_dataset_projectID_auth($tableMetadata)){
	break; //not authorized to view, stop showing anything else!
}


primary_links($tableMetadata, " -RESOLVED-"); //make HTML for primary links
other_links($tableMetadata, "none"); //make HTML links to other issues

html_page_top( "Data Documentation: Describe Fields / Columns" );

?>



<div class="data-doc-page-body">
	
	<!-- page heading information -->
	<div class="data-doc-page-heading">
		<div class="data-doc-page-heading-row">
			<div class="data-doc-page-heading-title">
				<h2>Field / Column Documentation</h2>
				<p>Issues and Summary Status: [<?php echo "<a href=\"../plugin.php?page=DataRefine/data-doc-summary&grProject=".$GRprojectID."\">Link</a>"; ?>]</p>
			</div>
			<div class="data-doc-page-heading-dset">
				<div class="data-doc-page-heading-dset-tab">
					<div class="data-doc-page-heading-dset-row">
						<div class="data-doc-page-heading-dset-title">
							<?php
							if(isset($tableMetadata["description"][0]["values"][0]["text"])){
								echo "<h3>&ldquo;".$tableMetadata["description"][0]["values"][0]["text"]."&rdquo;</h3>";
								echo "<br/><br/><span class=\"dest-sub-title\">(In refine as: <em>".$tableMetadata["name"]."</em>)</span>";	
							}
							else{
								echo "<h3>&ldquo;".$tableMetadata["name"]."&rdquo;</h3>";
							}
							
							?>
						</div>
						<div class="data-doc-page-heading-dset-des">
						This table currently has <span id="dataset-row-count"><?php echo $tableMetadata["refineRowCount"];  ?></span> rows. The last edit / modification of this table in Google Refine took place on <span id="dataset-last-modified"><?php echo date("F j, Y, g:i a", strtotime($tableMetadata["refineModified"]));  ?></span>. View the dataset in Google refine: [<a href="<?php echo $refineHumanURI."/project?project=".$GRprojectID;  ?>">Here</a>]
						<br/><br/>
						Currently, <span id="docRemaining"><?php echo $remainingCols ; ?></span> columns still require documentation, or indication that no documentation is needed.
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Main content for this dataset tracking page -->	
	<div class="data-doc-page-primary">

	<?php
		
		//only show this page if the edit resolved issue is done!
		if($tableMetadata["issueIDs"]["editResolved"]){
		
	?>

		<div class="fieldDes-outter-div">
			<input type="hidden" id="GRprojectID" value="<?php echo $GRprojectID; ?>" />
			<input type="hidden" id="numColumns" value="<?php echo count($tableMetadata["columns"]); ?>" />
			<input type="hidden" id="userID" value="<?php echo $u_username; ?>" />
			<br/>
			<div id="tableContainer" class="tableContainer">
			<table border="0" cellpadding="0" cellspacing="0" class="scrollTable" >
				<thead class="fixedHeader" >
				<tr>
					<th class="c_name">Column Name</th>
					<th class="c_vals">Sample Values</th>
					<th class="c_des">Description
					<br/><em>(Just type then click outside the box to update)</em>
					</th>
					<th class="c_units">Meaurement Units</th>
					<th class="c_stand">Rel. Standards</th>
				</tr>
				</thead>
				<tbody class="scrollContent">
				<?php
				
				$i = 0;
				foreach($tableMetadata["columns"] as $colArray){
					
					if ( $i&1 ){
						$style = "style='background-color:#ECF1EF;'";
					}
					else{
						$style = "";
					}
					
					echo "<tr ".$style.">\n";
					
					echo "<td class=\"c_name\">".$colArray["name"]."</td>\n";
					
					$sampleValId = $i.'_sample_val';
					$sampleDiv = "<div id='$sampleValId'></div>";
					//$sampleCommand = "<a href=\"javascript:getSampleValues('".$sampleValId."', '".$colArray["name"]."')\")'>Get Sample Values</a>";
					$sampleCommand = "<a id=\"".$i."_sample_val_cont\" href=\"javascript:getSampleValues($i, '".$colArray["name"]."')\")'>Get Sample Values</a>";
					
					echo "<td class=\"c_vals\">".$sampleDiv.$sampleCommand."</td>\n";
					
					$noteFound = false;
					$noteCreator = false;
					if(isset($colArray["note"])){
						
						$skipNote = $colArray["note"]["skipNote"];
						$noteCreator = $colArray["note"]["noteCreator"];
						
						if(isset($colArray["note"]["text"])){
							$noteText = $colArray["note"]["text"];
							if(strlen($noteText)>1){
								$noteFound = true;
							}
						}
					}
					else{
						$noteText = "";
					}
					
					echo "<td class=\"c_des\">";
					
					$noteInput = '<textarea id="'.$i.'_col_note" class="dataDocTextArea" onChange="addNote(this.id, '.$i.')">';
					$noteInput .= $noteText;
					$noteInput .= "</textarea>".chr(13);
					
					
					
					//now add controls to say no note is needed
					
					if(!$noteFound && !$skipNote){
						$noteInput .= "<div id=\"".$i."_no_note_needed\" class=\"no_note_needed\"><a href=\"javascript:skipNote(".$i.", '".$colArray["name"]."')\">Skip column documentation</a> (no note needed) </div>";
					}
					
					if($noteCreator != false && !$skipNote){
						$noteInput .= "<div id=\"".$i."_col_noteCreator\" class=\"noteCreator\">Note created by: ".$noteCreator."</div>";
					}
					elseif($noteCreator != false && $skipNote && !$noteFound){
						$noteInput .= "<div id=\"".$i."_col_noteCreator\" class=\"noteCreator\">Skip column documentation approved by: ".$noteCreator."</div>";
					}
					else{
						$noteInput .= "<div id=\"".$i."_col_noteCreator\" class=\"noteCreator\"></div>";
					}
					
					echo $noteInput;
			
			
			
			
			
					echo "</td>";
					
					
					echo "<td class=\"c_units\">";
					
					$units = "";
					
					if(!isset($colArray["unit"])){
						$units .= "<div id=\"".$i."_show_units\" class=\"add_units\"><a href=\"javascript:displayUnitChoices(".$i.", '".$colArray["name"]."')\">Units of measurement</a><br/>(if needed) </div>";
						$units .= "<div id=\"".$i."_rem_units\" class=\"rem_units_link\"></div>";
					}
					else{
						$units .= "<div id=\"".$i."_show_units\" class=\"show_units\">";
						$units .= "<strong>".$colArray["unit"]["unitName"]."</strong> [".$colArray["unit"]["unitType"]."]<br/>";
						$units .= "Defined at: <em><a href=\"".$colArray["unit"]["unitURI"]."\">".substr($colArray["unit"]["unitURI"],0,20)."...</a></em><br/>";
						$units .= "<div id=\"".$i."_col_unitCreator\" class=\"noteCreator\">Assignment by: ".$colArray["unit"]["noteCreator"]."</div>";
						$units .= "</div>";
						$units .= "<div id=\"".$i."_rem_units\" class=\"rem_units_link\"><br/><a href=\"javascript:removeUnitAssignment(".$i.", '".$colArray["name"]."')\">Remove unit of measurement</a></div>";
					}
		
		
		
					echo $units;
					
					
					
					echo "</td>\n";
					echo "<td class=\"c_stand\">";
					
					$standards = "";
					
					if(!isset($colArray["concept"])){
						$standards .= "<div id=\"".$i."_show_concepts\" class=\"add_units\"><a href=\"javascript:displayStandardsChoices(".$i.", '".$colArray["name"]."')\">Linked Data Standards</a><br/>(if needed) </div>";
						$standards .= "<div id=\"".$i."_rem_concepts\" class=\"rem_units_link\"></div>";
					}
					else{
						$standards .= "<div id=\"".$i."_show_concepts\" class=\"show_units\">";
						$standards .= "<strong>".$colArray["concept"]["conceptName"]."</strong> [".$colArray["concept"]["vocabName"]."]<br/>";
						$standards .= "Defined at: <em><a href=\"".$colArray["concept"]["conceptURI"]."\">".substr($colArray["concept"]["conceptURI"],0,20)."...</a></em><br/>";
						$standards .= "<div id=\"".$i."_col_unitCreator\" class=\"noteCreator\">Assignment by: ".$colArray["concept"]["noteCreator"]."</div>";
						$standards .= "</div>";
						$standards .= "<div id=\"".$i."_rem_concepts\" class=\"rem_units_link\"><br/><a href=\"javascript:removeConceptAssignment(".$i.", '".$colArray["name"]."')\">Remove this stand. concept</a></div>";
					}
		
		
		
					echo $standards;
					
					
					
					
					
					echo "</td>\n";
					echo "</tr>\n";
				
				$i++;
				}
				
				
				?>
				</tbody>
			</table>
			
			
			<!-- Now some wigits for Dojo -->
			<div id="paneArea" class="claro">
			</div>
			
			</div>
	
<?php

	}//end conditional where editissue is resolved
	else{
	
	?>
		<br/>
		<br/>
		<h2>So Sorry! This Dataset is Still Being Edited!</h2>
		<br/>
		<br/>
		<p>Fields / columns may change in the course of cleaning and editing this dataset with Google Refine. Because of this potential for change,
		it is premature to document fields / columns in this dataset.</p>
		<p>Please first complete edits in <a href="<?php echo $refineHumanURI."/project?project=".$GRprojectID;  ?>">Google Refine</a>. Once edits are completed,
		please update the status of <?php echo $editLink; ?> to 'resolved' or 'closed'. Once this issue has been updated, users may add documentation to fields /
		columns of this dataset.</p>
		<br/>
		<br/>
		<br/>
<?php		
	}//end conditional where the edit issue is NOT resolved
?>
</div>

	

<?php
html_page_bottom();
?>
